# -*- coding: utf-8 -*-
import sys
import time

from apps.utils.common import CommonUtils

reload(sys)
sys.setdefaultencoding("utf-8")


class RemoteTool(object):
    """ 远程操作工具类 """

    def __init__(self, logger, remote_host, remote_pass, remote_port):
        self.log = logger
        self.util = CommonUtils(self.log)
        self.remote_host = remote_host
        self.remote_pass = remote_pass
        self.remote_port = remote_port
        self.remote_disk_dir = None
        self.remote_disk_limit_percent = None
        self.remote_disk_check_secs = None

    # 额外参数配置
    def set_config(self, remote_disk_dir, remote_disk_limit_percent, remote_disk_check_secs):
        self.remote_disk_dir = remote_disk_dir
        self.remote_disk_limit_percent = remote_disk_limit_percent
        self.remote_disk_check_secs = remote_disk_check_secs

    # 执行远端shell命令，无返回
    def exec_remote_shell0(self, script):
        full_script = '''sshpass -p {} ssh -p {} {} {}'''.format(
            self.remote_pass, self.remote_port, self.remote_host, script)
        stat_code = self.util.exec_local_shell0(full_script)
        loop = 0
        while stat_code is not None and str(stat_code) != "0":
            loop += 1
            self.util.sleep_strategy(loop, 60, "远端执行命令失败")
            stat_code = self.util.exec_local_shell0(full_script)

    # 执行远端shell命令
    def exec_remote_shell(self, script):
        full_script = '''sshpass -p {} ssh -p {} {} {}'''.format(
            self.remote_pass, self.remote_port, self.remote_host, script)
        out, stat_code = self.util.exec_local_shell(full_script)
        loop = 0
        while stat_code is not None and str(stat_code) != "0" or len(out) == 0:
            loop += 1
            self.util.sleep_strategy(loop, 60, "远端命令执行失败")
            out, stat_code = self.util.exec_local_shell(full_script)
        return out

    # SCP传输文件到远端服务器
    def scp_to_remote(self, src_path, remote_addr):
        script = "sshpass -p {} scp -P {} -r {} {}".format(self.remote_pass, self.remote_port, src_path, remote_addr)
        stat_code = self.util.exec_local_shell0(script)
        loop = 0
        while stat_code is not None and str(stat_code) != "0":
            loop += 1
            self.util.sleep_strategy(loop, 60, "SCP传输文件到远端服务器异常")
            stat_code = self.util.exec_local_shell0(script)

    # 获取远端主机数据磁盘使用
    def remote_disk_size(self):
        script = '''df --block-size=KB | awk '$NF=="''' + self.remote_disk_dir + '''" {print $2" "$3" "$4" "$5}' '''
        out = self.exec_remote_shell(script)
        fields = out[0].strip().split(" ")
        total_kb = fields[0].replace("kB", "")
        used_kb = fields[1].replace("kB", "")
        avail_kb = fields[2].replace("kB", "")
        use_percent = fields[3]
        self.log.info("远端{}磁盘占用: total_kb: {}, Used_kb: {}, Available_kb: {}, Used%: {}".format(
            self.remote_disk_dir, total_kb, used_kb, avail_kb, use_percent))
        return total_kb, used_kb, avail_kb, use_percent

    # 远端数据目录磁盘使用校验
    def remote_check_disk(self, current_kb):
        total_kb, used_kb, avail_kb, use_percent = self.remote_disk_size()
        while (float(current_kb) + float(used_kb)) >= float(total_kb) * float(self.remote_disk_limit_percent):
            self.log.error("远端磁盘超过 {}! Current_kb: {}, Total_kb: {}, Used_kb: {}, Available_kb: {}, Used%: {}".format(
                self.remote_disk_limit_percent, current_kb, total_kb, used_kb, avail_kb, use_percent))
            time.sleep(self.remote_disk_check_secs)
            total_kb, used_kb, avail_kb, use_percent = self.remote_disk_size()

    # 获取远端指定路径大小
    def remote_file_size(self, path):
        # /data/ods_back/test
        script = "du -s {}".format(path)
        out = self.exec_remote_shell(script)
        return out[0].split("\t")[0]
